<template>
  <div class="region-management">
    <div class="header">
      <h2>区域管理</h2>
      <button @click="$router.push('/dashboard')" class="back-btn">返回首页</button>
    </div>
    
    <!-- 添加区域表单 -->
    <div class="add-region-form">
      <input v-model="newRegion.name" placeholder="区域名称" />
      <input v-model="newRegion.code" placeholder="区域编码" />
      <select v-model="newRegion.level">
        <option value="1">一级区域</option>
        <option value="2">二级区域</option>
        <option value="3">三级区域</option>
      </select>
      <select v-model="newRegion.parent_id">
        <option value="">选择上级区域</option>
        <option v-for="region in parentRegions" :key="region.id" :value="region.id">
          {{ region.name }}
        </option>
      </select>
      <select v-model="newRegion.manager_id">
        <option value="">选择区域经理</option>
        <option v-for="employee in employees" :key="employee.id" :value="employee.id">
          {{ employee.name }}
        </option>
      </select>
      <button @click="addRegion" :disabled="!isValidRegion">添加区域</button>
    </div>

    <!-- 区域列表 -->
    <table class="region-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>名称</th>
          <th>编码</th>
          <th>级别</th>
          <th>上级区域</th>
          <th>区域经理</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="region in regions" :key="region.id">
          <td>{{ region.id }}</td>
          <td>{{ region.name }}</td>
          <td>{{ region.code }}</td>
          <td>{{ getLevelName(region.level) }}</td>
          <td>{{ getParentName(region.parent_id) }}</td>
          <td>{{ getManagerName(region.manager_id) }}</td>
          <td>
            <span :class="['status-badge', region.status === 'active' ? 'active' : 'inactive']">
              {{ region.status === 'active' ? '启用' : '禁用' }}
            </span>
          </td>
          <td>
            <button @click="editRegion(region)">编辑</button>
            <button 
              @click="toggleRegionStatus(region)"
              :class="['status-btn', region.status === 'active' ? 'deactivate' : 'activate']"
            >
              {{ region.status === 'active' ? '禁用' : '启用' }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 编辑区域对话框 -->
    <div v-if="showEditDialog" class="edit-dialog">
      <div class="edit-dialog-content">
        <h3>编辑区域</h3>
        <div class="form-group">
          <label>区域名称：</label>
          <input v-model="editingRegion.name" />
        </div>
        <div class="form-group">
          <label>区域编码：</label>
          <input v-model="editingRegion.code" />
        </div>
        <div class="form-group">
          <label>区域级别：</label>
          <select v-model="editingRegion.level">
            <option value="1">一级区域</option>
            <option value="2">二级区域</option>
            <option value="3">三级区域</option>
          </select>
        </div>
        <div class="form-group">
          <label>上级区域：</label>
          <select v-model="editingRegion.parent_id">
            <option value="">选择上级区域</option>
            <option v-for="region in parentRegions" :key="region.id" :value="region.id">
              {{ region.name }}
            </option>
          </select>
        </div>
        <div class="form-group">
          <label>区域经理：</label>
          <select v-model="editingRegion.manager_id">
            <option value="">选择区域经理</option>
            <option v-for="employee in employees" :key="employee.id" :value="employee.id">
              {{ employee.name }}
            </option>
          </select>
        </div>
        <div class="dialog-buttons">
          <button @click="updateRegion">保存</button>
          <button @click="showEditDialog = false" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'RegionManagement',
  data() {
    return {
      regions: [],
      employees: [],
      newRegion: {
        name: '',
        code: '',
        level: '1',
        parent_id: '',
        manager_id: ''
      },
      showEditDialog: false,
      editingRegion: null
    }
  },
  computed: {
    isValidRegion() {
      return this.newRegion.name && this.newRegion.code && this.newRegion.level
    },
    parentRegions() {
      return this.regions.filter(region => region.level < this.newRegion.level)
    }
  },
  created() {
    this.fetchRegions()
    this.fetchEmployees()
  },
  methods: {
    getLevelName(level) {
      const levels = {
        '1': '一级区域',
        '2': '二级区域',
        '3': '三级区域'
      }
      return levels[level] || level
    },
    getParentName(parentId) {
      if (!parentId) return '无'
      const parent = this.regions.find(r => r.id === parentId)
      return parent ? parent.name : '未知'
    },
    getManagerName(managerId) {
      if (!managerId) return '未分配'
      const manager = this.employees.find(e => e.id === managerId)
      return manager ? manager.name : '未知'
    },
    async fetchRegions() {
      try {
        const response = await axios.get('/api/regions', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.regions = response.data
      } catch (error) {
        console.error('获取区域列表失败:', error)
        alert('获取区域列表失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async fetchEmployees() {
      try {
        const response = await axios.get('/api/employees', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.employees = response.data
      } catch (error) {
        console.error('获取员工列表失败:', error)
        alert('获取员工列表失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async addRegion() {
      if (!this.isValidRegion) {
        alert('请填写完整的区域信息')
        return
      }
      try {
        const response = await axios.post('/api/regions', this.newRegion, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchRegions()
        this.newRegion = { name: '', code: '', level: '1', parent_id: '', manager_id: '' }
        alert('添加区域成功')
      } catch (error) {
        console.error('添加区域失败:', error)
        alert('添加区域失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    editRegion(region) {
      this.editingRegion = { ...region }
      this.showEditDialog = true
    },
    async updateRegion() {
      try {
        await axios.put(`/api/regions/${this.editingRegion.id}`, this.editingRegion, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchRegions()
        this.showEditDialog = false
        alert('更新区域成功')
      } catch (error) {
        console.error('更新区域失败:', error)
        alert('更新区域失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async toggleRegionStatus(region) {
      try {
        const newStatus = region.status === 'active' ? 'inactive' : 'active'
        await axios.put(`/api/regions/${region.id}/status`, { status: newStatus }, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchRegions()
        alert(`区域${newStatus === 'active' ? '启用' : '禁用'}成功`)
      } catch (error) {
        console.error('更新区域状态失败:', error)
        alert('更新区域状态失败：' + (error.response?.data?.message || '未知错误'))
      }
    }
  }
}
</script>

<style scoped>
.region-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  padding: 8px 16px;
  background-color: #909399;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-region-form {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.region-table {
  width: 100%;
  border-collapse: collapse;
}

.region-table th,
.region-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.region-table th {
  background-color: #f5f5f5;
}

button {
  margin: 0 5px;
  padding: 5px 10px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #66b1ff;
}

button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-badge.active {
  background-color: #67c23a;
  color: white;
}

.status-badge.inactive {
  background-color: #f56c6c;
  color: white;
}

.status-btn {
  font-size: 12px;
}

.status-btn.activate {
  background-color: #67c23a;
}

.status-btn.deactivate {
  background-color: #f56c6c;
}

.edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.edit-dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn {
  background-color: #909399;
}

.cancel-btn:hover {
  background-color: #a6a9ad;
}
</style> 